package com.coolingme.notandor.expression.nonterminal;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.text.StrSplitter;
import com.coolingme.notandor.IExpression;
import com.coolingme.notandor.expression.KeywordExpression;
import com.coolingme.notandor.expression.operator.AndOperator;

import java.util.ArrayList;
import java.util.List;

/**
 * 并(+) 非终结符表达式
 *
 * @author wangyue
 * @date 2022/12/24 21:38
 */
public class AndExpression implements IExpression {

    /**
     * 并逻辑的操作表达式列表
     */
    private List<IExpression> andExpressionList = new ArrayList();

    public AndExpression(List<IExpression> expressions) {
        // 根据并操作符分割，默认分割后的都是独立的并操作符
        int[] andIndexArray = ListUtil.indexOfAll(expressions, AndOperator.getInstance()::equals);

        // 有或符号，保存或前后的表达式
        if (andIndexArray.length > 0) {
            int start = 0;
            int end;
            for (int orIndex : andIndexArray) {
                end = orIndex;
                // 分割并前后的表达式
                List<IExpression> expressionList = ListUtil.sub(expressions, start, end);
                this.andExpressionList.add(expressionList.get(0));
                start = orIndex + 1;
            }
            end = expressions.size();
            List<IExpression> expressionList = ListUtil.sub(expressions, start, end);
            this.andExpressionList.add(expressionList.get(0));
        } else {
            // 没有或符号，所有表达式作为并连接
            this.andExpressionList.add(expressions.get(0));
        }
    }

    public AndExpression(String strAndExpression) {
        List<String> keywordList = StrSplitter.splitByRegex(strAndExpression, "\\+", -1, true, true);
        for (String keyword : keywordList) {
            andExpressionList.add(new KeywordExpression(keyword));
        }
    }


    @Override
    public Boolean interpret(String content) {
        for (IExpression expression : this.andExpressionList) {
            // 并的语法为有一个不是true，就返回false
            if (!expression.interpret(content)) {
                return false;
            }
        }
        // 全部是true才返回true
        return true;
    }


}
